<?php
/**
*
* 功能描述（用户数据）
*
* @author suoya <jlusuoya@gmail.com>
* @version 1
*/

class ModelUser extends ModelBase
{
	function GetByMobile($mobile)
	{
		$where = "mobile = $mobile or name = $mobile";
		$data  = $this->db->getRow("user", 'id, mobile, name', $where);
		return $data;
	}

	function CreateUser($type, $mobile, $pwd, $data)
	{
		$data = array('type' => $type, 'mobile' => $mobile,
			'password' => md5($pwd), 'name' => $mobile,
			'email' => $mobile . " not set",
			'com_name' => $data['com_name'],
			'com_tel' => $data['com_tel'],
		);
		$id = $this->db->Insert("user", $data);
		return $id;
	}

	function Login($username, $pwd)
	{
		$where = "password = '" . md5($pwd) . "' and (mobile = '$username' or email = '$username' or name = '$username')";
		$data  = $this->db->getRow("user", 'id, mobile, name, level, type, com_name', $where);
		if($data)
			$this->db->Execute("update user set lastlogin = CURRENT_TIMESTAMP where id = " . $data['id']);
		return $data;
	}

	function GetAccInfo($id)
	{
		$data  = $this->db->getRow("user", 'mobile, email, round(money, 3) money, score, regtime, lastlogin, com_name, com_tel, type, level', "id = $id");
		return $data;
	}

	function GetInfo($val, $type)
	{
		if($type == 1)
			$where = "id = $val";
		else
			$where = "name = '$val'";
		$data  = $this->db->getRow("user", 'id, type usertype, level, name, mobile, email, truename, sex, bYear, bMonth, bDay, com_tel, com_name', $where);
		return $data;
	}

	function SaveInfo($id, $data)
	{
		$cnt = $this->db->Update("user", $data, "id = $id");
		return $cnt;
	}

	function SetKey($id, $key, $old)
	{
		$where = "id = $id";
		if($key == 0)
			$where .= " and `key` = $old";
		$data = array(
			'key' => $key,
		);
		$cnt = $this->db->Update("user", $data, $where);
		return $cnt;
	}

	function SetPwd($id, $pwd, $old='')
	{
		$data = array(
			'password' => md5($pwd),
		);
		$where = "`id` = $id";
		if($old != '')
			$where .= " and password = '".md5($old)."'";
		$cnt = $this->db->Update("user", $data, $where);
		return $cnt;
	}

	function DecScore($uid, $score)		//扣积分
	{
		$sql = "update user set score = score - $score where id = $uid and score >= $score";
		return $this->db->execute($sql);
	}

	function IncScore($uid, $score)		//加积分
	{
		$sql = "update user set score = score + $score where id = $uid";
		return $this->db->execute($sql);
	}

	function DecMoney($uid, $money)		//余额
	{
		$sql = "update user set money = money - $money where id = $uid && money >= $money";
		return $this->db->execute($sql);
	}
}

